package com.example.administrator.ygddriver.listen.grab;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.example.administrator.ygddriver.R;
import com.example.administrator.ygddriver.base.BaseActivity;
import com.example.administrator.ygddriver.base.BaseHint;
import com.example.administrator.ygddriver.base.UserBean;
import com.example.administrator.ygddriver.listen.GrabSingleRequestBean;
import com.example.administrator.ygddriver.listen.ListenRequestBean;
import com.example.administrator.ygddriver.liteorm.LiteOrmTools;
import com.example.administrator.ygddriver.map.DrivingRouteOverlay;
import com.example.administrator.ygddriver.map.SendMapActivity;
import com.example.administrator.ygddriver.netty.TcpClient;
import com.example.administrator.ygddriver.tool.OkGoRequests;
import com.example.administrator.ygddriver.tool.ScrollPickerView;
import com.example.administrator.ygddriver.tool.StringScrollPicker;
import com.example.administrator.ygddriver.tool.UrlValuse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.baidu.mapapi.utils.DistanceUtil.getDistance;

public class GrabActivity extends BaseActivity implements View.OnClickListener, OnGetRoutePlanResultListener {
    private StringScrollPicker mPickerHorizontal;
    private Button mBackBtn;
    private ListenRequestBean.ResultBean requestBean;
    private TextView mAddressTv, mNetworkLocationTv, mFreightTv, mBargainingTv, mNextTv, mTagTv;
    private String c_token, c_driver, bargaining = "0";
    private int pos;
    private Double longitude, latitude;
    private BaiduMap mBaiduMap;
    private MapView mMapView;
    // 搜索相关
    RoutePlanSearch mSearch = null;    // 搜索模块，也可去掉地图模块独立使用

    @Override
    public int initLayout() {
        return R.layout.activity_grab;
    }

    @Override
    public void initView() {
        mMapView = findViewById(R.id.item_fragment_listen_mv);
        mBaiduMap = mMapView.getMap();
        mBackBtn = findViewById(R.id.activity_grab_btn);
        mPickerHorizontal = findViewById(R.id.activity_grab_ssp);
        mAddressTv = findViewById(R.id.activity_grab_address_tv);
        mNetworkLocationTv = findViewById(R.id.activity_grab_grab_network_location_tv);
        mFreightTv = findViewById(R.id.activity_grab_freight_tv);
        mBargainingTv = findViewById(R.id.activity_grab_bargaining_tv);
        mNextTv = findViewById(R.id.activity_grab_next_tv);


        mTagTv = findViewById(R.id.activity_grab_tag_tv);
        mBackBtn.setOnClickListener(this);
        mNextTv.setOnClickListener(this);
        // 初始化搜索模块，注册事件监听
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);


    }

    @Override
    public void initDate() {
        LiteOrmTools.getInformation(UserBean.class, this, new LiteOrmTools.On<UserBean>() {
            @Override
            public void hasData(UserBean data) {
                c_token = data.getC_token();
                c_driver = data.getC_id();
            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {

            }
        });
        Bundle bundle = getIntent().getExtras();
        requestBean = bundle.getParcelable("requestBean");
        getDistance( Double.valueOf(requestBean.getC_customerlatitude()), Double.valueOf(requestBean.getC_customerlongitude()),Double.valueOf(requestBean.getC_latitude()), Double.valueOf(requestBean.getC_longitude()));
        pos = bundle.getInt("pos");
        mAddressTv.setText(requestBean.getC_address());
        if (requestBean.getC_bargaining().equals("0")) {
            mBargainingTv.setText("");
        } else {
            mBargainingTv.setText("已加价" + requestBean.getC_bargaining() + "元");
        }

        mFreightTv.setText(requestBean.getC_freight());
        mNetworkLocationTv.setText(requestBean.getC_networklocation());

        if (requestBean.getC_isbargaining().equals("1")) {
            mTagTv.setText("不可议价");
        } else if (requestBean.getC_isbargaining().equals("2")) {
            mTagTv.setText("可议价");
        }

        final List<CharSequence> newList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            String s = i + "";
            newList.add(Html.fromHtml(s));
        }
        mPickerHorizontal.setData(newList, 0);
        mPickerHorizontal.setOnSelectedListener(new ScrollPickerView.OnSelectedListener() {
            @Override
            public void onSelected(ScrollPickerView scrollPickerView, int position) {
                CharSequence money = newList.get(position);
                bargaining = money.toString();

            }
        });

    }

    //获取距离
    private void getDistance(Double startLat, Double startlon, Double endLat, Double endLon) {
        LatLng endLng = new LatLng(endLat, endLon);
        LatLng startLng = new LatLng(startLat, startlon);
        PlanNode enNodee = PlanNode.withLocation(endLng);
        PlanNode stNodee = PlanNode.withLocation(startLng);
        mSearch.drivingSearch((new DrivingRoutePlanOption())
                .from(enNodee).to(stNodee));

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_grab_btn:
                finish();
                break;
            case R.id.activity_grab_next_tv:
                initGrabSingleHtml(c_driver, requestBean.getC_customer(), requestBean.getC_waybill(), String.valueOf(requestBean.getC_grab()), requestBean.getC_waybillnum(), requestBean.getC_valuation(), bargaining, requestBean.getC_isbargaining(), requestBean.getC_orderid(), c_token);
                break;
        }
    }

    //司机端抢单
    private void initGrabSingleHtml(String c_driver, final String c_customer, String c_id, String c_grab, String c_waybillnum, String c_valuation, String c_bargaining, String c_isbargaining, String c_orderid, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_driver", c_driver);
        hashMap.put("c_customer", c_customer);
        hashMap.put("c_id", c_id);
        hashMap.put("c_grab", c_grab);
        hashMap.put("c_waybillnum", c_waybillnum);
        hashMap.put("c_valuation", c_valuation);
        hashMap.put("c_bargaining", c_bargaining);
        hashMap.put("c_isbargaining", c_isbargaining);
        hashMap.put("c_orderid", c_orderid);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", "2");
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_DRIVER + UrlValuse.GRAB_SINGLE, hashMap, GrabSingleRequestBean.class, new OkGoRequests.OnTrue<GrabSingleRequestBean>() {
            @Override
            public void hasData(GrabSingleRequestBean date) {
                if (date.isSuccess()) {
                    // 抢单(可议价 c_account 用户端账号唯一标识  c_operation 操作类型)
                    String msg6 = "{c_account:" + c_customer + ",c_operation:6}&";
                    TcpClient instance_t = TcpClient.getInstance();
                    instance_t.sendMsgByByete(msg6);
                    Intent intent = new Intent();
                    intent.putExtra("pos", pos);
                    //返回结果
                    setResult(0x001, intent);
                    //关闭当前界面
                    finish();
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(GrabActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }

            }
        }, new OkGoRequests.OnError<GrabSingleRequestBean>() {
            @Override
            public void noData() {

            }
        });


    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
        if (drivingRouteResult == null || drivingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
        }
        if (drivingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            // result.getSuggestAddrInfo()
            Toast.makeText(this, "抱歉，起终点或途经点地址有岐义", Toast.LENGTH_SHORT).show();
            return;
        }
        if (drivingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
            if (drivingRouteResult.getRouteLines().size() > 1) {
                int distance = 0;
                int pos = 0;
                for (int i = 0; i < drivingRouteResult.getRouteLines().size(); i++) {
                    if (distance == 0) {
                        pos = i;
                        distance = drivingRouteResult.getRouteLines().get(i).getDistance();
                    } else if (distance <= drivingRouteResult.getRouteLines().get(i).getDistance()) {

                    } else if (distance > drivingRouteResult.getRouteLines().get(i).getDistance()) {
                        distance = drivingRouteResult.getRouteLines().get(i).getDistance();
                        pos = i;
                    }
                }
                DrivingRouteLine drivingRouteLine = drivingRouteResult.getRouteLines().get(pos);
                DrivingRouteOverlay overlay = new DrivingRouteOverlay(mBaiduMap);
                overlay.setData(drivingRouteLine);
                overlay.addToMap();
                overlay.zoomToSpan();

            }
        } else if (drivingRouteResult.getRouteLines().size() == 1) {
            DrivingRouteLine route = drivingRouteResult.getRouteLines().get(0);
            route.getDistance();
            DrivingRouteOverlay overlay = new DrivingRouteOverlay(mBaiduMap);
            overlay.setData(route);
            overlay.addToMap();
            overlay.zoomToSpan();

        } else {
            Log.d("route result", "结果数<0");
            return;
        }
    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

    }


}
